{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 说明\n",
    "\n",
    "对比几种解析库：\n",
    "\n",
    "- [python-hl7](https://github.com/johnpaulett/python-hl7) 很不友好，索引全部使用下标，不容易理解\n",
    "\n",
    "- [hl7-parser](https://github.com/mps-gmbh/hl7-parser)：比较好用，所有字段都可以用英文含义索引，可以修改数据。不能直接获取含有数据的字段，需要遍历\n",
    "\n",
    "- [HL7py](https://github.com/norlowski/HL7py)：跟前者相似，可以通过英文含义索引，👍**能以字典的方式返回所有数据的字段**。 支持重新组装、构建hl7数据包。  \n",
    "**兼容性差，容易解析失败**。而且需要做 2to3 转换。时间字段解析结果可能跟预想不一样。\n",
    "\n",
    ">本人对HL7协议并没有深入研究过，也不了解每个字段的含义，仅仅是为了满足工作需求，将自己对 解析工具的使用过程展现给大家，如有描述错误，不必太过计较。😜😜"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# HL7协议测试数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "message = 'MSH|^~\\&|GHH LAB|ELAB-3|GHH OE|BLDG4|200202150930||ORU^R01|CNTRL-3456|P|2.4\\r'\n",
    "message += 'PID|||555-44-4444||EVERYWOMAN^EVE^E^^^^L|JONES|196203520|F|||153 FERNWOOD DR.^^STATESVILLE^OH^35292||(206)3345232|(206)752-121||||AC555444444||67-A4335^OH^20030520\\r'\n",
    "message += 'PV1||I|W^389^1^UABH^^^^3||||12345^MORGAN^REX^J^^^MD^0010^UAMC^L||67890^GRAINGER^LUCY^X^^^MD^0010^UAMC^L|MED|||||A0||13579^POTTER^SHERMAN^T^^^MD^0010^UAMC^L|||||||||||||||||||||||||||200605290900'\n",
    "message += 'OBR|1|845439^GHH OE|1045813^GHH LAB|1554-5^GLUCOSE|||200202150730||||||||555-55-5555^PRIMARY^PATRICIA P^^^^MD^^LEVEL SEVEN HEALTHCARE, INC.|||||||||F||||||444-44-4444^HIPPOCRATES^HOWARD H^^^^MD\\r'\n",
    "message += 'OBX|1|SN|1554-5^GLUCOSE^POST 12H CFST:MCNC:PT:SER/PLAS:QN||^182|mg/dl|70_105|H|||F'\n",
    "message +=  'OBX||NM|AG_FiO2||21.00|%|18.00-100.00||||\\r'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "message = 'MSH|^~\\&|||||20080521104435||ORU^R01|||2.3.1\\r'\\\n",
    "            'PID||001|001||zhang^san||20091010|M\\r' \\\n",
    "            'PV1||U|^^Bed1|||||||||||||||adult||||||||||||||||||||||||||20091111\\r'\\\n",
    "            'OBR|||||||20170426111902\\r' \\\n",
    "            'OBX||NM|HR||80|bmp |60-100\\r'\\\n",
    "            'OBX||NM|AG_FiCO2||0.10|%|0.00-0.50||||\\r'\\\n",
    "            'OBX||NM|AG_EtO2||19.00|%|0.00-100.00||||\\r'\\\n",
    "            'OBX||NM|AG_FiO2||21.00|%|18.00-100.00||||\\r'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# [python-hl7](https://github.com/johnpaulett/python-hl7)\n",
    "\n",
    "这个。。。真不好使\n",
    "\n",
    ">pip install -U hl7\n",
    "\n",
    "## 基本用法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import hl7\n",
    "\n",
    "h = hl7.parse(message)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[['PID'],\n",
       " [''],\n",
       " ['001'],\n",
       " ['001'],\n",
       " [''],\n",
       " [[['zhang'], ['san']]],\n",
       " [''],\n",
       " ['20091010'],\n",
       " ['M']]"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 按下标获取一个段\n",
    "h[1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 索引方式 vs 调用\n",
    "h[1][2][0] == h(2)(3)(1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(True, True, True)"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 以下几种索引方式效果一样\n",
    "h[1] == h['PID'][0],  h['PID'] == h.segments('PID'), h['PID'][0] == h.segment('PID')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'zhang^san'"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 转为字符串\n",
    "str(h[1][5])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'001'"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 索引到具体值\n",
    "h[1][2][0]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# [hl7parser](https://github.com/mps-gmbh/hl7-parser)(推荐）\n",
    "\n",
    ">pip install hl7parser\n",
    "\n",
    "## 基本用法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "message = 'MSH|^~\\&|GHH LAB|ELAB-3|GHH OE|BLDG4|200202150930||ORU^R01|CNTRL-3456|P|2.4\\r'\n",
    "message += 'EVN||200605290901||||200605290900\\r'\n",
    "message += 'PID|||555-44-4444||EVERYWOMAN^EVE^E^^^^L|JONES|196203520|F|||153 FERNWOOD DR.^^STATESVILLE^OH^35292||(206)3345232|(206)752-121||||AC555444444||67-A4335^OH^20030520\\r'\n",
    "message += 'PV1||U|^^Bed1|||||||||||||||adult||||||||||||||||||||||||||20091111\\r'\n",
    "message += 'OBR|1|845439^GHH OE|1045813^GHH LAB|1554-5^GLUCOSE|||200202150730||||||||555-55-5555^PRIMARY^PATRICIA P^^^^MD^^LEVEL SEVEN HEALTHCARE, INC.|||||||||F||||||444-44-4444^HIPPOCRATES^HOWARD H^^^^MD\\r'\n",
    "message += 'OBX|1|SN|1554-5^GLUCOSE^POST 12H CFST:MCNC:PT:SER/PLAS:QN||^182|mg/dl|70_105|H|||F\\r'\n",
    "message += 'OBX|2|NM|^Body Weight||79|kg^Kilogram^ISO+|||||F'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<hl7parser.hl7.HL7Message at 0x1679a42feb8>"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import hl7parser\n",
    "from hl7parser.hl7 import HL7Message\n",
    "msg = HL7Message(message)\n",
    "msg"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'|^~\\\\&'"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "str(msg.delimiters)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'CNTRL-3456'"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "str(msg.type)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'MSH|^~\\\\&|GHH LAB|ELAB-3|GHH OE|BLDG4|200202150930||ORU^R01|CNTRL-3456|P|2.4|'"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "str(msg.header)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'2.4'"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "str(msg.msh.version_id)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'MSH|^~\\\\&|GHH LAB|ELAB-3|GHH OE|BLDG4|200202150930||ORU^R01|CNTRL-3456|P|2.4\\rEVN||200605290901||||200605290900\\rPID|||555-44-4444||EVERYWOMAN^EVE^E^^^^L|JONES|196203520|F|||153 FERNWOOD DR.^^STATESVILLE^OH^35292||(206)3345232|(206)752-121||||AC555444444||67-A4335^OH^20030520\\rPV1||U|^^Bed1|||||||||||||||adult||||||||||||||||||||||||||20091111\\rOBR|1|845439^GHH OE|1045813^GHH LAB|1554-5^GLUCOSE|||200202150730||||||||555-55-5555^PRIMARY^PATRICIA P^^^^MD^^LEVEL SEVEN HEALTHCARE, INC.|||||||||F||||||444-44-4444^HIPPOCRATES^HOWARD H^^^^MD\\rOBX|1|SN|1554-5^GLUCOSE^POST 12H CFST:MCNC:PT:SER/PLAS:QN||^182|mg/dl|70_105|H|||F\\rOBX|2|NM|^Body Weight||79|kg^Kilogram^ISO+|||||F'"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "msg.message"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"{'msh': 0, 'evn': 1, 'pid': 2, 'pv1': 3, 'obr': 4, 'obx': [5, 6]}\""
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 数据段信息\n",
    "str(msg.segment_position)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[('msh', <hl7parser.hl7.HL7Segment at 0x1679a42f978>),\n",
       " ('evn', <hl7parser.hl7.HL7Segment at 0x1679bdd7ef0>),\n",
       " ('pid', <hl7parser.hl7.HL7Segment at 0x1679bdf3dd8>),\n",
       " ('pv1', <hl7parser.hl7.HL7Segment at 0x1679be02588>),\n",
       " ('obr', <hl7parser.hl7.HL7Segment at 0x1679be05278>),\n",
       " ('obx', <hl7parser.hl7.HL7Segment at 0x1679be24908>),\n",
       " ('obx', <hl7parser.hl7.HL7Segment at 0x1679be276a0>)]"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 所有 数据段 对象列表，用来迭代\n",
    "msg.segments"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "adult 20091111\n",
      "2.4\n"
     ]
    }
   ],
   "source": [
    "# 通过下标位置索引\n",
    "print(str(msg.pv1[17]), str(msg.pv1[43]))\n",
    "print(str(msg.msh[10]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "PV1||U|^^Bed1|||||||||||||||123||||||||||||||||||||||||||20091111|\n"
     ]
    }
   ],
   "source": [
    "# 也可以修改\n",
    "msg.pv1[17] = '123'\n",
    "print(msg.pv1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2.4\n",
      "EVERYWOMAN^EVE^E^^^^L\n",
      "^^Bed1\n",
      "200202150730\n"
     ]
    }
   ],
   "source": [
    "# 通过属性(英文含义）索引\n",
    "print(str(msg.msh.version_id))\n",
    "print(str(msg.pid.patient_name))\n",
    "print(str(msg.pv1.assigned_patient_location))\n",
    "print(str(msg.obr.observation_datetime))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "EVERYWOMAN^EVE^E^^^^L\n",
      "EVE\n"
     ]
    }
   ],
   "source": [
    "# repeating fields\n",
    "print(msg.pid.patient_name)\n",
    "print(str(msg.pid.patient_name[0][1]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'set_id': 0,\n",
       " 'placer_order_number': 1,\n",
       " 'filler_order_number': 2,\n",
       " 'universal_service_identifier': 3,\n",
       " 'priority': 4,\n",
       " 'requested_datetime': 5,\n",
       " 'observation_datetime': 6}"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 查看数据段的简略信息 { xxx属性: index }\n",
    "# msg.msh.named_fields\n",
    "# msg.pv1.named_fields\n",
    "msg.obr.named_fields"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[('set_id',\n",
       "  {'required': False,\n",
       "   'repeats': False,\n",
       "   'type': hl7parser.hl7_data_types.HL7DataType,\n",
       "   'index': None}),\n",
       " ('placer_order_number',\n",
       "  {'required': False,\n",
       "   'repeats': False,\n",
       "   'type': hl7parser.hl7_data_types.HL7DataType,\n",
       "   'index': None}),\n",
       " ('filler_order_number',\n",
       "  {'required': False,\n",
       "   'repeats': False,\n",
       "   'type': hl7parser.hl7_data_types.HL7DataType,\n",
       "   'index': None}),\n",
       " ('universal_service_identifier',\n",
       "  {'required': False,\n",
       "   'repeats': False,\n",
       "   'type': hl7parser.hl7_data_types.HL7DataType,\n",
       "   'index': None}),\n",
       " ('priority',\n",
       "  {'required': False,\n",
       "   'repeats': False,\n",
       "   'type': hl7parser.hl7_data_types.HL7DataType,\n",
       "   'index': None}),\n",
       " ('requested_datetime',\n",
       "  {'required': False,\n",
       "   'repeats': False,\n",
       "   'type': hl7parser.hl7_data_types.HL7DataType,\n",
       "   'index': None}),\n",
       " ('observation_datetime',\n",
       "  {'required': False,\n",
       "   'repeats': False,\n",
       "   'type': hl7parser.hl7_data_types.HL7Datetime,\n",
       "   'index': None})]"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 查看某个数据段的详细字段属性，以及是否为必须字段、是否允许重复、其数据类型等等\n",
    "msg.obr.field_definitions\n",
    "# msg.msh.field_definitions   # MSH\n",
    "# msg.pid.field_definitions   # PID\n",
    "# msg.pv1.field_definitions   # PV1\n",
    "# msg.obr.field_definitions   # OBR\n",
    "# msg.obx[0].field_definitions   # 存在多个OBX时"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# by name or index\n",
    "msg.evn[1] == msg.evn.recorded_datetime"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[('message_code',\n",
       "  {'required': True,\n",
       "   'repeats': False,\n",
       "   'type': hl7parser.hl7_data_types.HL7DataType,\n",
       "   'index': None}),\n",
       " ('trigger_event',\n",
       "  {'required': True,\n",
       "   'repeats': False,\n",
       "   'type': hl7parser.hl7_data_types.HL7DataType,\n",
       "   'index': None}),\n",
       " ('message_structure',\n",
       "  {'required': True,\n",
       "   'repeats': False,\n",
       "   'type': hl7parser.hl7_data_types.HL7DataType,\n",
       "   'index': None})]"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 部分 字段属性可能有子属性，可通过 field_map 继续查看详细\n",
    "msg.msh.message_type.field_map\n",
    "# hl7parser.hl7_data_types.HL7_PersonLocation.field_map"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ORU^R01 - ORU - R01\n"
     ]
    }
   ],
   "source": [
    "# 举例\n",
    "print(str(msg.msh.message_type),'-', str(msg.msh.message_type.message_code), '-', str(msg.msh.message_type.trigger_event))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ORU^R01 - ORU - R01\n"
     ]
    }
   ],
   "source": [
    "print(str(msg.msh[7]),'-', str(msg.msh.message_type[0]), '-', str(msg.msh.message_type[1]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "hl7parser.hl7_data_types.HL7Datetime"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 查看数据类型\n",
    "msg.evn.recorded_datetime.__class__"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['component_map',\n",
       " 'datetime',\n",
       " 'field_map',\n",
       " 'isNull',\n",
       " 'isoformat',\n",
       " 'precision',\n",
       " 'set_attributes']"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 查看该数据类型支持的方法\n",
    "list(filter(lambda x: not x.startswith('__'), dir(msg.evn.recorded_datetime)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2006-05-29T09:01:00\n"
     ]
    }
   ],
   "source": [
    "# 举例\n",
    "print(msg.evn.recorded_datetime.isoformat())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "hl7parser.hl7_data_types.HL7_ExtendedPersonName"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# repeating fields\n",
    "type(msg.pid.patient_name[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# [HL7py](https://github.com/norlowski/HL7py)\n",
    "\n",
    "下载源码包，解压，然后用以下命令 ， 将 py2文件转换成py3 文件，再安装\n",
    "```sh\n",
    "2to3 -w HL7py\n",
    "python3 setup.py install\n",
    "```\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 基本用法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [],
   "source": [
    "from HL7py import parser"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [],
   "source": [
    "message = 'MSH|^~\\&|GHH LAB|ELAB-3|GHH OE|BLDG4|200202150930||ORU^R01|CNTRL-3456|P|2.4\\r'\n",
    "message += 'PID|||555-44-4444||EVERYWOMAN^EVE^E^^^^L|JONES|196203520|F|||153 FERNWOOD DR.^^STATESVILLE^OH^35292||(206)3345232|(206)752-121||||AC555444444||67-A4335^OH^20030520\\r'\n",
    "message += 'PV1||I|W^389^1^UABH^^^^3||||12345^MORGAN^REX^J^^^MD^0010^UAMC^L||67890^GRAINGER^LUCY^X^^^MD^0010^UAMC^L|MED|||||A0||13579^POTTER^SHERMAN^T^^^MD^0010^UAMC^L|||||||||||||||||||||||||||200605290900'\n",
    "message += 'OBR|1|845439^GHH OE|1045813^GHH LAB|1554-5^GLUCOSE|||200202150730||||||||555-55-5555^PRIMARY^PATRICIA P^^^^MD^^LEVEL SEVEN HEALTHCARE, INC.|||||||||F||||||444-44-4444^HIPPOCRATES^HOWARD H^^^^MD\\r'\n",
    "message += 'OBX|1|SN|1554-5^GLUCOSE^POST 12H CFST:MCNC:PT:SER/PLAS:QN||^182|mg/dl|70_105|H|||F'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<HL7py.parser.Message at 0x1679be3bd30>"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "msg = parser.parse(message, custom_levels={'OBR':1,'OBX':2})\n",
    "msg"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "HL7py.parser.Segment"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(msg.MSH)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'MSH'"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 获取数据段名\n",
    "msg.MSH.code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "MSH|^~\\&|GHH LAB|ELAB-3|GHH OE|BLDG4|200202150930||ORU^R01|CNTRL-3456|P|2.4|||||||\n",
      "2.4\n"
     ]
    }
   ],
   "source": [
    "# hl7属性： 获取该节点的字符串(注意： 此处容易翻车😂)\n",
    "print(msg.MSH.hl7)\n",
    "print(msg.MSH.version.hl7)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'code': 'MSH',\n",
       " 'encoding_chars': '^~\\\\&',\n",
       " 'send_app': {'app_name': 'GHH LAB'},\n",
       " 'send_fac': 'ELAB-3',\n",
       " 'recv_app': {'app_name': 'GHH OE'},\n",
       " 'recv_fac': 'BLDG4',\n",
       " 'timestamp': datetime.datetime(2002, 2, 15, 9, 30),\n",
       " 'security': '',\n",
       " 'msg_type': {'message_code': 'ORU', 'event_code': 'R01'},\n",
       " 'msg_ctl_id': 'CNTRL-3456',\n",
       " 'proc_id': 'P',\n",
       " 'version': '2.4',\n",
       " 'seq_no': '',\n",
       " 'cont_pointer': '',\n",
       " 'accept_ack_type': '',\n",
       " 'application_ack_type': '',\n",
       " 'country_code': '',\n",
       " 'character_set': '',\n",
       " 'principal_lang_of_msg': ''}"
      ]
     },
     "execution_count": 38,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# data属性：一键获取所有数据段，返回一个嵌套字典\n",
    "\n",
    "msg.MSH.data\n",
    "# msg.PID.data\n",
    "# msg.EVN.data\n",
    "# msg.IN1.data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'street': '153 FERNWOOD DR.',\n",
       " 'street2': '',\n",
       " 'city': 'STATESVILLE',\n",
       " 'state': 'OH',\n",
       " 'zip': '35292',\n",
       " 'country': '',\n",
       " 'addr_type': '',\n",
       " 'other': '',\n",
       " 'other2': ''}"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "msg.PID.pat_address.data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "STATESVILLE\n",
      "200605290900OBR\n"
     ]
    }
   ],
   "source": [
    "# data: 若没有子节点直接返回数据\n",
    "print(msg.PID.pat_address.city.data)\n",
    "print(msg.PV1.admit_dt_tm.data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " PV1\n",
      "     OBX\n"
     ]
    }
   ],
   "source": [
    "# 节点树状图\n",
    "msg.PV1.fmt_tree()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "OBX|1|SN|1554-5^GLUCOSE^POST 12H CFST:MCNC:PT:SER/PLAS:QN||^182|mg/dl|70_105|H|||F||||\n"
     ]
    }
   ],
   "source": [
    "# 如果有子节点（OBX 节点）\n",
    "obx = msg.PV1.child_segments[0]\n",
    "print(obx.hl7)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 构建一个完整 hl7 数据包\n",
    "from HL7py.parser import Message, Segment\n",
    "import datetime"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u000b",
      "MSH|^~\\&|ANKHOS||Their App||202005141812||ADT^A08||P|2.3|||AL|AL|||\r",
      "EVN|R01|202005141812^S||||\r",
      "PID|||||^^||||||^^^^^^^^||^^^^|^^^^||||||||||||||||\r",
      "PV1|||^^^^^^^^||||^^^^^^^^^&&^&&^|^^^^^^^^^&&^&&^||||||||||||||||||||||||||||||||||||||||||||\u001c",
      "\r\n"
     ]
    }
   ],
   "source": [
    "msg = Message()\n",
    "\n",
    "msh_data = dict(recv_app={'app_name': 'Their App'},\n",
    "                send_app={'app_name': 'ANKHOS'},\n",
    "                msg_type=dict(message_code='ADT', event_code='A08'),\n",
    "                accept_ack_type='AL',\n",
    "                application_ack_type='AL',\n",
    "                proc_id='P',\n",
    "                version='2.3',\n",
    "                encoding_chars='^~\\&',\n",
    "                timestamp=datetime.datetime.now())\n",
    "MSH = Segment(code='MSH', data=msh_data)\n",
    "evn_data = dict(event_code='R01',\n",
    "                timestamp=dict(time=datetime.datetime.now(), resolution='S'))\n",
    "EVN = Segment(code='EVN', data=evn_data)\n",
    "PID = Segment(code='PID', data={})\n",
    "pv1_data = {}\n",
    "PV1 = Segment(code='PV1', data=pv1_data)\n",
    "msg.add_segments([MSH, EVN, PID, PV1])\n",
    "\n",
    "#Voila!\n",
    "print(msg.hl7)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {
    "height": "calc(100% - 180px)",
    "left": "10px",
    "top": "150px",
    "width": "189.6px"
   },
   "toc_section_display": true,
   "toc_window_display": true
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
